package com.xo.so.jsouplocal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.xo.so.Variables;
import com.xo.so.vanthan.ItemListProvinceEntity;

public class JsoupProvince {

	private void getValueCity(Element element, int dem) {
		Elements elements2 = element.select("a");
		for (Element element2 : elements2) {
			String ten_tinh = element2.text(), ten_link = element2.attr("href");
			switch (dem % 2) {
			case 0:
				if (!Variables.lstMienNam.containsKey(ten_tinh)) {
					Variables.lstMienNam.put(ten_tinh,
							new ItemListProvinceEntity(ten_tinh, ten_link));
					// Log.e("Item:",
					// Variables.lstMienNam.get(ten_tinh).getTen_tinh()+"\n"+
					// Variables.lstMienNam.get(ten_tinh).getUrlTinh()+"\n");
				}
				break;

			default:
				Variables.lstMienTrung.put(ten_tinh,
						new ItemListProvinceEntity(ten_tinh, ten_link));
				// Log.e("Item:",
				// Variables.lstMienNam.get(ten_tinh).getTen_tinh()+"\n"+
				// Variables.lstMienNam.get(ten_tinh).getUrlTinh()+"\n");
				break;
			}

			// ten_tinh.split(" ");// cat chuoi
			// ItemListProvinceEntity entity = new ItemListProvinceEntity(
			// ten_tinh, "");
			// Log.e("tinh", ten_tinh);
			// mItemProvince.add(entity);
		}
	}

	private ArrayList<ItemListProvinceEntity> reslut(
			HashMap<String, ItemListProvinceEntity> hasmap) {
		ArrayList<ItemListProvinceEntity> mItemProvince = new ArrayList<ItemListProvinceEntity>();

		for (Entry<String, ItemListProvinceEntity> entry : hasmap.entrySet()) {
			mItemProvince.add(entry.getValue());

		}
		return mItemProvince;

	}

	public ArrayList<ItemListProvinceEntity> parseJsoupProvince(String url,
			int index_nav) {

		try {
			url = Variables.site;
			Document document = Jsoup.connect(url).ignoreHttpErrors(true).get();
			Elements elements = document.select("td.LMT_2");
			int dem = 0;
			for (Element element : elements) {
				getValueCity(element, dem);
				dem++;
			}
			switch (index_nav) {
			case 1:
				return reslut(Variables.lstMienNam);
			case 2:
				return reslut(Variables.lstMienTrung);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
